package com.netafull.twitter;

import java.util.ArrayList;
import java.util.List;

import com.netafull.R;
import com.netafull.ShowAdActivity;
import com.netafull.analyze.AnalyzeXMLForUrl;
import com.netafull.analyze.Content;
import com.netafull.analyze.News;
import com.netafull.analyze.ShortUrl;
import com.netafull.util.CloseUtil;

import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class TwitterPage extends ShowAdActivity {
	ImageButton btn_back;
	ImageButton btn_sendToTwitter;
	ImageButton btn_userChange;

	TextView mTwitterCanshu;
	EditText mTwitterEdit;

	String uTitle = "";
	int uId = 0;
	String url = "";
	String uAnalyzeUrl = "";
	int uLength = 140;
	News ns;
	
	String shortUrl = "";
	List<ShortUrl> list;
	AnalyzeXMLForUrl analyze;

	//AnalyzeXML analyzeXML;
	public ProgressDialog myDialog = null;
	private List<Content> li = new ArrayList<Content>();

	TwitterConnect tc;
	String nechatterStatus = "";
	SharedPreferences pref;
	ProgressDialog progressDialog;
	ProgressDialog progressDialog2;
	ProcessHandle phand;
	Bitmap imbm = null;
	int uCount = 0;
	String sButtonState = "";
	
	Intent intent;
	
	boolean b = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.twitterpage);
		
		show();
		
		CloseUtil.activityList.add(TwitterPage.this);
		
		analyze = new AnalyzeXMLForUrl();
		
		mTwitterCanshu = (TextView) findViewById(R.id.twittercanshu);
		btn_userChange = (ImageButton) findViewById(R.id.twitterchange);
		mTwitterEdit = (EditText) findViewById(R.id.twittercontent);
		
		
		btn_back = (ImageButton) findViewById(R.id.twitterpage_button_left);
		btn_sendToTwitter = (ImageButton) findViewById(R.id.twitterpage_button_right);

		//analyzeXML = new AnalyzeXML();
		//ns = new News();
		intent = this.getIntent();
		//Bundle bundle = intent.getExtras();
		uTitle = intent.getExtras().getString("title");
		uId = intent.getExtras().getInt("id");
		url = intent.getExtras().getString("url");
		//mTwitterEdit.setText(uTitle + " " + url);
		Log.e("caget", "uId = " + uId);
		phand = new ProcessHandle();
		tc = new TwitterConnect(TwitterPage.this);
		progressDialog = new ProgressDialog(TwitterPage.this);
		progressDialog.setTitle("Please wait...");
		progressDialog.setMessage("Please wait...");
		progressDialog.setIndeterminate(true);

		progressDialog2 = new ProgressDialog(TwitterPage.this);
		progressDialog2.setTitle("Please wait...");
		progressDialog2.setMessage("Please wait...");
		progressDialog2.setIndeterminate(true);
		// twitter 连接状态
		pref = getSharedPreferences(CONST.PREFERENCE_NAME, MODE_PRIVATE);
		nechatterStatus = pref.getString("status", "");
		//setContentView(R.layout.twitterpage);

		sButtonState = pref.getString("buttonstate", "");
		if (!sButtonState.equals("true")) {
			btn_userChange.setEnabled(false);
		}
		

		btn_back = (ImageButton) findViewById(R.id.twitterpage_button_left);
		btn_sendToTwitter = (ImageButton) findViewById(R.id.twitterpage_button_right);
		btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		btn_sendToTwitter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				uCount++;
				Log.e("caget", "nechatterStatus = " + nechatterStatus);
				if (isConnected(nechatterStatus)) {
					Log.e("caget", "1111111");
					new ProcessThread().start();
					GetUserInfoTask gt = new GetUserInfoTask();
					gt.execute("");
				}
			}
		});
		btn_userChange.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				b = true;
				Intent it = new Intent();
				it.setClass(TwitterPage.this, TwitterLoginBrowser.class);
				startActivityForResult(it, 1);
			}
		});
		mTwitterEdit.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				String s = mTwitterEdit.getText().toString();
				int t = uLength - s.length();
				String tt = String.valueOf(t);
				mTwitterCanshu.setText("残数" + " " + tt);
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}

		});
		
		//mTwitterEdit.setText(uTitle + " " + url);

		final Handler myHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					System.out.println("有没有执行"+uTitle+url);
					mTwitterEdit.setText(uTitle + "\n" + shortUrl+" |ネタフル|\n#netafull");
					url = "";
					myDialog.dismiss();

					break;
				case 1:

					break;
				}
				super.handleMessage(msg);
			}
		};
		myDialog = ProgressDialog.show(TwitterPage.this, "", getResources()
				.getString(R.string.loading), true);
		new Thread() {
			public void run() {
				try {
					if(uId==0){
						uId = intent.getExtras().getInt("id");
					}
					//String path = "http://api.bit.ly/v3/shorten?&login=byokanmonday&apiKey=R_a8f37383b661bc046909ca16f1a684d7&longUrl=http://stg.byokanmonday.dev.vc/news/?id="+ uId + "&format=xml";
					String path = "http://api.bit.ly/v3/shorten?&login=netafull&apiKey=R_8826b2745cfe264aa2047bd73277479b&longUrl=http://netafull.dev.vc/report/?id="+uId+"&format=xml"+"&device=Android";
					System.out.println("uid="+uId);
					list = analyze.getRss(path);
					if(list.size()!=0){
						shortUrl = list.get(0).getUrl();
						System.out.println("--------------->"+shortUrl);
					}
				} catch (Exception e) {
					Log.e("caget", "Analyze TwitterUrl Exception");

					e.printStackTrace();
				} finally {
					Message m = new Message();
					m.what = 0;
					myHandler.sendMessage(m);
					System.out.println("start send");
					// 验证
					if (!isConnected(nechatterStatus)) {
						sendMessage();

					}

				}
			}
		}.start();
	}

	// 验证的线程
	private void sendMessage() {
		// TODO Auto-generated method stub
		Send send = new Send();
		send.start();
	}

	class Send extends Thread {
		@Override
		public void run() {
			try {
				Send.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				b = true;
				Intent it = new Intent();
				it.setClass(TwitterPage.this, TwitterLoginBrowser.class);
				startActivityForResult(it, 1);
			}
		}
	}

	// 返回
	@Override
	public void onResume() {
		super.onResume();
	}

	/**
	 * twitter 连接状态确认
	 */
	final private boolean isConnected(String nechatterStatus) {
		if (nechatterStatus != null && nechatterStatus.equals("available")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 控制 转轮 线程
	 * 
	 * @author Administrator
	 * 
	 */
	class ProcessThread extends Thread {
		public void run() {
			if (!progressDialog.isShowing()) {
				Message msg = phand.obtainMessage();
				msg.arg1 = 1;
				phand.sendMessage(msg);
			}

		}
	}

	/**
	 * 如果用户处于登陆状态，获取用户头像跟name
	 * 
	 * @author Administrator
	 * 
	 */
	public class GetUserInfoTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			String re = "";

			ConfigurationBuilder confBuild = new ConfigurationBuilder();
			confBuild.setOAuthConsumerKey(CONST.CONSUMER_KEY);
			confBuild.setOAuthConsumerSecret(CONST.CONSUMER_SECRET);
			confBuild.setOAuthAccessToken(pref.getString("oauth_token", ""));
			confBuild.setOAuthAccessTokenSecret(pref.getString(
					"oauth_token_secret", ""));
			Configuration config = confBuild.build();

			if (TwitterConnect.twitter != null)
				TwitterConnect.twitter.shutdown();
			TwitterConnect.twitter = new TwitterFactory(config).getInstance();
			try {
				TwitterConnect.accessToken = TwitterConnect.twitter
						.getOAuthAccessToken();
				boolean bTest = false;
				if (tc == null) {
					tc = new TwitterConnect(TwitterPage.this);
					String test = String.valueOf(mTwitterEdit.getText()
							.toString());
					bTest = tc.TwitterContribute(test);
				} else {
					String test = String.valueOf(mTwitterEdit.getText()
							.toString());
					bTest = tc.TwitterContribute(test);
				}
				if (bTest) {
					re = "ok";
				} else {
					re = "failure";
				}

			} catch (TwitterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return re;
		}

		protected void onCancelled() {
			super.onCancelled();

			progressDialog.dismiss();
		}

		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			if (!result.equals("ok")) {
				Log.e("caget", "send failure!!!!");
				Toast.makeText(TwitterPage.this, "Get user info failure",
						Toast.LENGTH_LONG).show();
			} else {
				// ((ImageView)
				// findViewById(R.id.userimg)).setImageBitmap(imbm);
				// ((TextView)findViewById(R.id.username)).setText(pref.getString("username","null"));
				Log.e("caget", "send ok!!!!");
				Toast.makeText(TwitterPage.this, "The message send ok",
						Toast.LENGTH_LONG).show();
			}
			TwitterPage.this.finish();
		}

		@Override
		protected void onPreExecute() {

		}

		protected void onProgressUpdate(Integer... values) {

		}
	}

	/**
	 * 转轮 handle
	 */
	class ProcessHandle extends Handler {
		public void handleMessage(Message msg) {
			if (msg.arg1 == 1)
				progressDialog.show();
			else {
				progressDialog2.show();
			}
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		b = false;
		switch (resultCode) {
		case 1:
			Log.e("caget", "onActivityResult");
			nechatterStatus = pref.getString("status", "");
			sButtonState = pref.getString("buttonstate", "");
			if (sButtonState.equals("true")) {
				btn_sendToTwitter.setEnabled(true);
			}
			/*
			 * Bundle cbd = data.getExtras(); nechatterStatus =
			 * cbd.getString("status"); new ProcessThread().start();
			 * GetUserInfoTask gt = new GetUserInfoTask(); gt.execute("");
			 */
			break;
		}
	}
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();
		if(!b){
			System.out.println("开始销毁Activity");
			CloseUtil.closeActivity();
		}else{
			System.out.println("没有销毁Activity");
		}
	}
}
